#include "ParticleSystem.h"
#include "GFuns.h"

ParticleSystem::ParticleSystem(EParticleEffect aEffect, Node aSource)
{
	actualEffect = aEffect;
	source = aSource;

	if(actualEffect == PARTICLE_SMOKE)
	{
		maxParticles = 50;
		direction = -PI/2;
		disorder = PI/4;
		minSpeed = 0.1;
		maxSpeed = 0.2;
	}

	for(unsigned int i=0; i<maxParticles; i++)
		AddParticle(true);
}

ParticleSystem::~ParticleSystem()
{
}

void ParticleSystem::AddParticle(bool aStarting)
{
	if(actualEffect == PARTICLE_SMOKE)
	{
		Point pi;
		pi.x = source.x;
		pi.y = source.y;
		Particle p(randInt(50,70),color.carpetD,pi,randInterval(minSpeed,maxSpeed),randInterval(direction-disorder,direction+disorder));
		if(aStarting) p.time = rand()%(p.life+1);
		particles.push_back(p);
	}
}

void ParticleSystem::Tick()
{
	for(unsigned int i=0; i<particles.size(); i++)
	{
		particles[i].time++;
		particles[i].position.x += particles[i].speed.x;
		particles[i].position.y += particles[i].speed.y;
		particles[i].a = (1.0 - ((float)particles[i].time/(float)particles[i].life))*255;

		if(particles[i].time > particles[i].life)
		{
			particles.erase(particles.begin() + i);
			i--;
		}
	}

	if(particles.size() < maxParticles)
	{
		int toAdd = maxParticles - particles.size();
		for(int i=0; i<toAdd; i++) AddParticle();
	}
}